﻿using DB;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrainTicketBookingSystem
{
    internal class SeatService
    {
        public List<Seat> FindSeatByTrainId(int TrainId)
        {
            List<Seat> seatsList = new List<Seat>();

            string sql = " select * from seat where trainId = @TrainId ";
            MySqlDataReader reader = MySqlUtil.ExecutQuery(sql,new MySqlParameter("@TrainId",TrainId));

            while (reader.Read()) 
            {
                int seatId = reader.GetInt32("seatId");
                int trainId = reader.GetInt32("trainId");
                int carriageId = reader.GetInt32("carriageId");
                int seatNum = reader.GetInt32("seatNum");
                string status = reader.GetString("status");

                seatsList.Add(new Seat(seatId,carriageId,trainId,seatNum,status));
            }

            return seatsList;
        }

        //index = 0 一等座，index = 1 二等座
        public int BuySuitableSeat(int index,int trainId)
        {
            List<Seat> seatsList = new List<Seat>();

            string sql = "select * from seat join carriage on seat.carriageId = carriage.carriageId " + 
                " where carriage.trainId = @trainId and price = @price1 or price = @price2 limit 1 " ;

            MySqlDataReader reader = MySqlUtil.ExecutQuery(sql, 
                new MySqlParameter("@trainId",trainId),
                new MySqlParameter("@price1",index == 0 ? 800 : 400),
                new MySqlParameter("@price2",index == 0 ? 200 : 150));

            if (reader.Read())
            {
                int SeatId = reader.GetInt32("seatId");
                string sql1 = " update seat set status = '预定' where seatId = @seatId ";
                MySqlUtil.ExecutQuery(sql1, new MySqlParameter("@seatId", SeatId));
                return SeatId;
            }
            return 1;
        }
    }
}
